package com.huawei.app.httpapi;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.huawei.app.demo.util.LogUtils;

/**
 * HTTP API心跳线程
 *
 * @since 2021-01-06
 */
public class HeartbeatTask implements Runnable {

    private static final String TAG = HeartbeatTask.class.getSimpleName();
    private boolean isRunning = true;

    private ConcurrentMap<String, MsgRspCallback> msgNameMap = new ConcurrentHashMap<>();
    private ConcurrentMap<Integer, MsgRspCallback> msgIdMap = new ConcurrentHashMap<>();

    public HeartbeatTask() {
    }

    @Override
    public void run() {
        while (isRunning) {
            try {
                HttpApiResult apiResult = IdeaHubHttpApiUtils.getInstance().getMailboxData();
                if (!apiResult.isSuccess()) {
                    LogUtils.getInstance().e(TAG, "get mailbox data failed, apiResult is " + apiResult);
                    ThreadPools.pause(1000);
                    continue;
                }

                JSONArray msgArray = apiResult.getData().getJSONObject("msgStruct").getJSONArray("msg");
                if (msgArray.isEmpty()) {
                    LogUtils.getInstance().v(TAG, "get mailbox data success, msg is empty.");
                    ThreadPools.pause(1000);
                    continue;
                }

                for (int i=0; i<msgArray.size(); i++) {
                    JSONObject msgObj = msgArray.getJSONObject(i);

                    MsgRspCallback callback = null;
                    String msgName = msgObj.getString("msgName");
                    if (msgName != null && !msgName.trim().isEmpty()) {
                        callback = msgNameMap.get(msgName);
                    }
                    if (callback == null) {
                        callback = msgIdMap.get(msgObj.getInteger("msgID"));
                    }
                    if (callback == null) {
                        // 没有找到消息处理类, 忽略当前消息, 继续处理下一个消息
                        continue;
                    }
                    callback.handleMsg(msgObj);
                }

                LogUtils.getInstance().v("HeartbeatTask", "http api heartbeat task running.");
                ThreadPools.pause(1000);
            } catch (Exception e) {
                // ignore.
            }
        }
    }

    public void registerMsgCall(MsgRspCallback callback) {
        if (callback.getMsgName() != null && !callback.getMsgName().trim().isEmpty()) {
            msgNameMap.put(callback.getMsgName(), callback);
        }
        if (callback.getMsgId() != -1) {
            msgIdMap.put(callback.getMsgId(), callback);
        }
    }

    public void unregisterMsgCall(Integer msgId, String msgName) {
        if (msgName != null && !msgName.trim().isEmpty()) {
            msgNameMap.remove(msgName);
        }
        if (msgId != -1) {
            msgIdMap.remove(msgId);
        }
    }

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean running) {
        isRunning = running;
    }
}
